package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.GroupManager;
import cn.stylefeng.guns.modular.robot.service.GroupManagerService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Update;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional
public class CmdRemoveManager extends AbstractCmd {

    @Resource
    private GroupManagerService groupManagerService;

    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        Long chatId = update.getMessage().getChatId();
        String text = update.getMessage().getText();
        String[] split = text.split(" @");
        if (split.length < 2) {
            return;
        }
        List<GroupManager> groupManagers = groupManagerService.lambdaQuery()
                .eq(GroupManager::getGroupId, chatId)
                .in(GroupManager::getUserName, Arrays.asList(split))
                .list();
        if (CollectionUtils.isEmpty(groupManagers)) {
            return;
        }
        groupManagerService.removeByIds(groupManagers.stream().map(GroupManager::getId).collect(Collectors.toSet()));
        List<GroupManager> allGroupManager = groupManagerService.lambdaQuery()
                .eq(GroupManager::getGroupId, chatId)
                .list();
        String userNames = allGroupManager.stream().map(GroupManager::getUserName).collect(Collectors.joining(","));
        RobotUtils.sendText(chatId, "本群管理员: " + userNames, bot);
    }

    @Override
    public String getCmdName() {
        return "删除操作人";
    }

    @Override
    public String getDescribe() {
        return "删除操作人                删除群管理员，如：删除操作人 @张三\n";
    }
}
